/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
#include "arm_math.h"
#include "message.h"
#include "stm32_hal_legacy.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

extern uint8_t UserTxBufferFS[APP_TX_DATA_SIZE];
extern USBD_HandleTypeDef hUsbDeviceFS;
extern uint8_t UsbReceive[10];
extern uint8_t UsbSend[10];
extern uint8_t UsbRecCpt;

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define ADC_SHIFT 2048
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
uint32_t DMA_adc2mem[4]; 
uint8_t IICAddr;
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint8_t AngleDataSend = 0;
uint32_t Set_Value = 0;
uint32_t Get_Value = 0;
uint32_t Dac_state = 0;
uint32_t Dac_Error = 0;
uint16_t Tim3SetValue = 0;
float Angle = 0;
float Anglebuff = 0;
float CordicIn[2];
float	cordic_outf;
uint16_t CompareValue = 0;

uint8_t  conv_cmpt = 0x00;     //complete adc conversion 
int32_t SensorAngle = 0;
int32_t SensorAngleFiltered = 0;
uint8_t  AdcConvertCount = 0x00;  

int16_t RawData[2] = {0,0};

uint32_t Usart17BitAngle = 0;

uint8_t uart_rx_buffer[10];

extern osSemaphoreId_t ADCcompleteHandle;

//typedef struct 
//{
//	double la;
//	float K1_8;
//	float K2_8;
//    float K3_8;         /* Added @2024.06.28 */
//	
//	float alpha_a;
//	float beta_a;	
//    float gamma_a;      /* Added @2024.06.28 */
//}KAL_Config_Integer_ParaType;

//KAL_Config_Integer_ParaType KAL_Para_Integer;

//uint32_t kal_filter_Integer(KAL_Config_Integer_ParaType* cfg, uint32_t xin);

//int32_t alpha_a_Integer = 65536;
//int32_t beta_a_Integer = 0;
//int32_t gamma_a_Integer = 0;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
//uint32_t kal_filter_Integer(KAL_Config_Integer_ParaType* cfg, uint32_t xin)
//{
//    int32_t    xi;

//    int32_t da = 0;

//    int64_t tmp0,tmp1,tmp2,tmp3;

//    da = xin - alpha_a_Integer;

//    /* Numerical continuity */
//    if (da <= -65536)
//    {
//        xi = xin + 131072;
//    }
//    else if (da >= 65536)
//    {
//        xi = xin - 131072;
//    }
//    else
//    {
//        xi = xin;
//    }

//	/*
//    kal_param[0][0] = 968567;
//    kal_param[0][1] = 24;
//    kal_param[0][2] = 0;
//    kal_param[0][3] = 80008;

//    kal_param[1][0] = -126988751;
//    kal_param[1][1] = 1045401;
//    kal_param[1][2] = 26;
//    kal_param[1][3] = 126988750;

//    kal_param[2][0] = -2519446;
//    kal_param[2][1] = -63;
//    kal_param[2][2] = 1048575;
//    kal_param[2][3] = 2519445;
//    */
//	
//	/*
//    kal_param[0][0] = 1022483;
//    kal_param[0][1] = 63;
//    kal_param[0][2] = 0;
//    kal_param[0][3] = 26092;

//    kal_param[1][0] = -5259816;
//    kal_param[1][1] = 1048247;
//    kal_param[1][2] = 65;
//    kal_param[1][3] = 5259815;

//    kal_param[2][0] = -33135;
//    kal_param[2][1] = -3;
//    kal_param[2][2] = 1048575;
//    kal_param[2][3] = 33134;
//    */
//	
//    tmp0 = alpha_a_Integer;
//    tmp0 = tmp0 * 1022483;  // tmp0 = tmp0 * kal_param[0][0];

//    tmp1 = beta_a_Integer;
//    tmp1 = tmp1 * 63;  //tmp1 = tmp1 * kal_param[0][1];

//    tmp2 = gamma_a_Integer;
//    tmp2 = tmp2 * 0;  //tmp2 = tmp2 * kal_param[0][2];

//    tmp3 = xi;
//    tmp3 = tmp3 * 26092;  //tmp3 = tmp3 * kal_param[0][3];

//    tmp3 = tmp3 + tmp2 + tmp1 + tmp0;

//    cfg->alpha_a = tmp3>>20;  
//    ////////////////////////////////////////

//    tmp0 = alpha_a_Integer;
//    tmp0 = tmp0 * -5259816;     //tmp0 = tmp0 * kal_param[1][0];

//    tmp1 = beta_a_Integer;
//    tmp1 = tmp1 * 1048247;     //tmp1 = tmp1 * kal_param[1][1];

//    tmp2 = gamma_a_Integer;
//    tmp2 = tmp2 * 65;     //tmp2 = tmp2 * kal_param[1][2];

//    tmp3 = xi;
//    tmp3 = tmp3 * 5259815;     //tmp3 = tmp3 * kal_param[1][3];

//    tmp3 = tmp3 + tmp2 + tmp1 + tmp0;

//    cfg->beta_a = tmp3 >> 20;
//    //////////////////////////////////////////////
//    tmp0 = alpha_a_Integer;
//    tmp0 = tmp0 * -33135;   //tmp0 = tmp0 * kal_param[2][0];

//    tmp1 = beta_a_Integer;
//    tmp1 = tmp1 * -3;   //tmp1 = tmp1 * kal_param[2][1];

//    tmp2 = gamma_a_Integer;
//    tmp2 = tmp2 * 1048575;   //tmp2 = tmp2 * kal_param[2][2];

//    tmp3 = xi;
//    tmp3 = tmp3 * 33134;   //tmp3 = tmp3 * kal_param[2][3];

//    tmp3 = tmp3 + tmp2 + tmp1 + tmp0;

//    cfg->gamma_a = tmp3 >> 20;

//    //////////////////////////////////////////////

//    /* the angle must be [0, 2PI) */
//    if (cfg->alpha_a < 0)
//    {
//        cfg->alpha_a += 131072;
//    }
//    else if (cfg->alpha_a >= 131072)
//    {
//        cfg->alpha_a -= 131072;
//    }

//    alpha_a_Integer = cfg->alpha_a;
//    beta_a_Integer = cfg->beta_a;
//    gamma_a_Integer = cfg->gamma_a;

//    return cfg->alpha_a;
//}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
	
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC2_Init();
  MX_DAC1_Init();
  MX_ADC1_Init();
  MX_TIM2_Init();
  MX_USB_Device_Init();
  MX_I2C2_Init();
  MX_I2C1_Init();
  MX_SPI1_Init();
  MX_TIM3_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
		
//	HAL_ADCEx_Calibration_Start(&hadc1,ADC_DIFFERENTIAL_ENDED);
//    HAL_ADCEx_Calibration_Start(&hadc2,ADC_DIFFERENTIAL_ENDED);

//	HAL_ADCEx_MultiModeStart_DMA(&hadc1,DMA_adc2mem,1);
				
    HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_2);
		HAL_TIM_Base_Start_IT(&htim2);
	
			//TIM3 OC Compare
		HAL_TIM_Base_Start(&htim3);
//		HAL_TIM_OC_Start(&htim3,TIM_CHANNEL_2);	
		if(HAL_TIM_OC_Start(&htim3,TIM_CHANNEL_2)!=HAL_OK){
			Error_Handler();
		}
		HAL_DAC_Start(&hdac1,DAC_CHANNEL_2);
//	    if (HAL_UARTEx_ReceiveToIdle_DMA(&huart1, uart_rx_buffer, 8) != HAL_OK) {
//        Error_Handler();
//    }

  /* USER CODE END 2 */

  /* Init scheduler */
  osKernelInitialize();

  /* Call init function for freertos objects (in freertos.c) */
  MX_FREERTOS_Init();

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

//	HAL_Delay(10);
//	do_reg0(0x00,0x24,0,8);
//	HAL_Delay(10);
//	do_reg0(0x80,0x24,0x5,0x1f);
//	HAL_Delay(10);
//	do_reg0(0x80,0x25,0x01,0x80);
//	HAL_Delay(10);
//	do_reg0(0x00,0x25,0x0,0x0f);
//	HAL_Delay(10);	
	
	//osKernelStart();

  while (1)
  {
		conv_cmpt++;
//		if(conv_cmpt)			//ADC1 conversion cmpt
//		{
//			conv_cmpt= 0x00;
//			
//			RawData[0] = ADC_SHIFT - *((int16_t*)&DMA_adc2mem+1);   //msin
//	    RawData[1] = *(int16_t*)&DMA_adc2mem - ADC_SHIFT;       //mcos
//			
//			CordicIn[0] = (float)RawData[0];
//			CordicIn[1] = (float)RawData[1];
//			
//			cordic_outf = atan2f(CordicIn[1],CordicIn[0]); 
//			Angle =	cordic_outf*57.295779513f;
//			
//			Anglebuff = Angle < 0 ? Angle + 360: Angle; 
//			
//			SensorAngle = Anglebuff* 364.088889f;
//			SensorAngle = SensorAngle < 0 ? SensorAngle + 131071 : SensorAngle;			
//			SensorAngleFiltered =kal_filter_Integer(&KAL_Para_Integer,SensorAngle);		
//		}			
//			/********************DAC*********************/
//		else{		
//				Set_Value = SensorAngleFiltered*4095/131071;				
//	    if (HAL_DAC_SetValue(&hdac1,DAC_CHANNEL_2,DAC_ALIGN_12B_R,Set_Value) != HAL_OK) {
//        Error_Handler();
//			}	
//			/*********************Tim3 ch2**********************/	
//			TIM_OC_InitTypeDef	sConfigOC;
//			sConfigOC.OCMode = TIM_OCMODE_COMBINED_PWM1;
//			Tim3SetValue=SensorAngleFiltered*9999/131071;
//			sConfigOC.Pulse = Tim3SetValue;
//			sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
//			sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
//			if (HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
//			{
//				Error_Handler();
//			}
//		}

//			/*********************Usart1**********************/
////			Usart17BitAngle = SensorAngleFiltered;
////			HAL_UART_Transmit_DMA(&huart1,(uint8_t*)&Usart17BitAngle,4);
////			/*********************IIC1**********************/
////			HAL_I2C_Master_Transmit(&hi2c1,0x54, (uint8_t*)&Usart17BitAngle, 4, 2);
////			/*********************SPI**********************/
////			HAL_SPI_Transmit_DMA(&hspi1,(uint8_t*)&Usart17BitAngle,4);
//			/********************USB*********************/
//			if(UsbRecCpt==1)
//			{
//				UsbRecCpt = 0;
//				if((UsbReceive[0]==0x5a)&&(UsbReceive[1]==0x55))
//				{
//					USBD_CDC_SetTxBuffer(&hUsbDeviceFS, (uint8_t*)&SensorAngleFiltered, 4);
//					USBD_CDC_TransmitPacket(&hUsbDeviceFS);
//				}				
//			}
			/***********************SPI**********************/		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSI48;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV4;
  RCC_OscInitStruct.PLL.PLLN = 75;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV4;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
//	portENTER_CRITICAL();
//	osSemaphoreRelease(ADCcompleteHandle);
//  portEXIT_CRITICAL();
}


void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	
	uint8_t rxBuffer[10];
	if (huart->Instance == USART1) {
			
			memcpy(rxBuffer, uart_rx_buffer, Size);
			ProcessReceivedData(rxBuffer, Size);
			
		if (HAL_UARTEx_ReceiveToIdle_DMA(huart, uart_rx_buffer, 8) != HAL_OK) {
					Error_Handler();
			}
	}
}





/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM4 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM4) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
